package com.tencent.wxcloudrun.service;

import com.tencent.wxcloudrun.utils.FileKit;
import com.tencent.wxcloudrun.utils.FilePathUtils;
import com.tencent.wxcloudrun.utils.ImageUtils;
import com.tencent.wxcloudrun.utils.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


/**
 * @author lichongbing
 * @version 1.0.0
 * @createdate 2023/2/20 07:18
 * @description: TODO
 */
@Service
public class UploadService {
    @Autowired
    private UpYunStorage upYunStorage;
    protected void validateFile(MultipartFile file) throws Exception {
        if (file == null || file.isEmpty()) {
            throw new Exception("文件不能为空");
        }

        if (!FileKit.checkFileType(file.getOriginalFilename())) {
            throw new Exception("文件格式不支持");
        }
    }

    public String writeToStore(byte[] bytes, String src, String originalFilename) throws Exception {
        String md5 = MD5.md5(bytes);
        String path = FilePathUtils.wholePathName(src, originalFilename, md5);
        path = upYunStorage.writeToStore(bytes, path);
        return path;
    }
    public String storeScale(MultipartFile file, String basePath, int width, int height) throws Exception {
        validateFile(file);
        byte[] bytes = ImageUtils.screenshot(file, width, height);
        return writeToStore(bytes, basePath, file.getOriginalFilename());
    }
}
